package com.example.mvpdemo.exception;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.mvpdemo.retrofit.HttpUtils;
import com.example.mvpdemo.util.AppUtils;
import com.example.mvpdemo.util.Constants;
import com.example.mvpdemo.util.FileManager;
import com.example.mvpdemo.util.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;


/**
 * @auth: njb
 * @date: 2022/11/20 10:24
 * @desc:
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "CrashLog";
    /**
     * 系统默认的UncaughtException处理类
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    /**
     * CrashHandler实例
     */
    private static volatile CrashHandler mInstance;

    // 使用Properties来保存设备的信息和错误堆栈信息
    private Properties mDeviceCrashInfo = new Properties();
    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";
    private static final String DEVICE_TYPE = "DEVICE_TYPE";
    private static final String DEVICE_ID = "DEVICE_ID";
    private static final String SYSTEM_VERSION = "SYSTEM_VERSION";

    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPORTER_EXTENSION = ".txt";
    private Context mContext;


    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        if (mInstance == null) {
            synchronized (CrashHandler.class) {
                if (mInstance == null) {
                    mInstance = new CrashHandler();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
     */
    public void init(Context context) {
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.mContext = context;

        // mCacheUtil = CacheUtil.getInstance(ctx);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable ex) {
        // 如果用户没有处理则让系统默认的异常处理器来处理
        // mDefaultHandler.uncaughtException(thread, ex);
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            // Sleep一会后结束程序
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error : ", e);
            }
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex 异常
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return true;
        }
        final String msg = ex.getLocalizedMessage();
        // 使用Toast来显示异常信息
 /*       new Thread() {
            @Override
            public void run() {
                // Toast 显示需要出现在一个线程的消息队列中
                Looper.prepare();
                ToastUtils.showShort("程序出错啦!!!" + msg);
                Looper.loop();
            }
        }.start();*/
        // 收集设备信息
        collectCrashDeviceInfo();
        // 保存错误报告文件
        saveCrashInfoToFile(ex);
        // 发送错误报告到服务器
        //sendPreviousReportsToServer();
        return true;
    }

    /**
     * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer(mContext);
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     */
    private void sendCrashReportsToServer(Context ctx) {
        String[] crFiles = getCrashReportFiles();
        String filePath = "/storage/emulated/0/Android/data/com.example.mvpdemo/files/log/crash-1669813906885.txt";
        LogUtils.d(TAG, "---文件名称---:" + crFiles);
        if (crFiles != null && crFiles.length > 0) {
            TreeSet<String> sortedFiles = new TreeSet<>(Arrays.asList((crFiles)));
            for (String fileName : sortedFiles) {
                File cr = new File(FileManager.getLogRootPath(), fileName);
                cr.delete(); // 删除已发送的报告
            }
        }
        postReport(new File(filePath));
    }

    private void postReport(File file) {
        // 使用HTTP Post 发送错误报告到服务器
        // 这里不再详述,开发者可以根据OPhoneSDN上的其他网络操作
        // 教程来提交错误报告
        Map<String, String> map = new HashMap<>();
        map.put("feedbackId", "7");
        Map<String, File> fileMap = new HashMap<>();
        fileMap.put("fileName", file);
            HttpUtils.postFiles(Constants.BASE_SERVER_URL + Constants.UPLOAD_LOG_URL, map, fileMap, new HttpUtils.OnRequestCallBack() {
                @Override
                public void onSuccess(String json) {
                    String data = json;
                    LogUtils.d(TAG, "---请求成功---" + data);
                }

                @Override
                public void onError(String errorMsg) {
                    LogUtils.e(TAG, "---请求失败---" + errorMsg);
                }
            });
    }

    /**
     * 缓存崩溃日志文件
     *
     * @param fileName
     */
    private void cacheCrashFile(String fileName) {
        SharedPreferences sp = mContext.getSharedPreferences("crash", Context.MODE_PRIVATE);
        sp.edit().putString("CRASH_FILE_NAME", fileName).commit();
    }


    /**
     * 获取崩溃文件名称
     *
     * @return
     */
    public File getCrashFile() {
        String crashFileName = mContext.getSharedPreferences("crash",
                Context.MODE_PRIVATE).getString("CRASH_FILE_NAME", "");
        return new File(crashFileName);
    }

    /**
     * 获取错误报告文件名
     */
    private String[] getCrashReportFiles() {
        File filesDir = new File(FileManager.getLogRootPath());
        FilenameFilter filter = (dir, name) -> name.endsWith(CRASH_REPORTER_EXTENSION);
        return filesDir.list(filter);
    }

    /**
     * 保存错误信息到文件中
     */
    private String saveCrashInfoToFile(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        String result = info.toString();
        printWriter.close();
        mDeviceCrashInfo.put(STACK_TRACE, result);
        mDeviceCrashInfo.put(DEVICE_ID, AppUtils.getDeviceId(mContext));
        mDeviceCrashInfo.put(DEVICE_TYPE, AppUtils.getPhoneModel());
        mDeviceCrashInfo.put(SYSTEM_VERSION, AppUtils.getSystemVersion());
        String fileName = "";
        try {
            long timestamp = System.currentTimeMillis();
            fileName = "crash-" + timestamp + CRASH_REPORTER_EXTENSION;
            String filename2 = "crash-" + timestamp + CRASH_REPORTER_EXTENSION;
            File file = new File(FileManager.getLogRootPath(), filename2);
            // 再从新创建文件夹
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream trace = new FileOutputStream(file);
            //mDeviceCrashInfo.store(trace, "");
            trace.write(result.getBytes());
            trace.flush();
            trace.close();
            return fileName;
            // 发送错误报告到服务器
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "an error occured while writing report file..." + fileName, e);
        }
        return null;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful. If a
     * deletion fails, the method stops attempting to delete and returns
     * "false".
     */
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            File[] children = dir.listFiles();
            // 递归删除目录中的子目录下
            for (File child : children) {
                child.delete();
            }
        }
        // 目录此时为空，可以删除
        return true;
    }

    /**
     * 收集程序崩溃的设备信息
     */
    public void collectCrashDeviceInfo() {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                mDeviceCrashInfo.put(VERSION_NAME, pi.versionName == null ? "not set" : pi.versionName);
                mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
                mDeviceCrashInfo.put(DEVICE_ID, AppUtils.getDeviceId(mContext));
                mDeviceCrashInfo.put(DEVICE_TYPE, AppUtils.getPhoneModel());
                mDeviceCrashInfo.put(SYSTEM_VERSION, AppUtils.getSystemVersion());
            }
        } catch (
                PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        // 使用反射来收集设备信息.在Build类中包含各种设备信息,
        // 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
        // 具体信息请参考后面的截图
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null));
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }
    }
}
